# -*- coding: utf-8 -*-
import os

from django.conf import settings
from django.shortcuts import get_object_or_404
from django.views.generic import ListView
from django.views.generic import DeleteView
from django.views.generic.edit import CreateView
from django.views.generic.edit import UpdateView
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _

from mediabox.lira.utils import get_messages
from mediabox.lira.utils import set_messages
from mediabox.lira.utils import get_msgfile
from mediabox.lira.utils import Transliterator

from mediabox.lira.models import Program
from mediabox.lira.forms import ProgramForm

class ProgramNew(CreateView):
    form_class = ProgramForm
    success_url = '/manage/programs'
    template_name = 'commom_validation_error.html'

    def form_valid(self, form):
        msg_filename = get_msgfile(self.request)
        messages = [{'type': 'success', 'message': _('Program saved'), }]

        if set_messages(filename=msg_filename, messages=messages):
            self.request.session['msg_file'] = msg_filename

        self.make_folder(self.request.POST['title'])

        return super(ProgramNew, self).form_valid(form)

    def form_invalid(self, form):
        msg_filename = get_msgfile(self.request)
        messages = [{'type': 'errormsg', 'message': _('Please fill in the forms correctly'), }]

        if set_messages(filename=msg_filename, messages=messages):
            self.request.session['msg_file'] = msg_filename

        return super(ProgramNew, self).form_invalid(form)

    def get_context_data(self, **kwargs):
        context = super(ProgramNew, self).get_context_data(**kwargs)

        if self.request.session.has_key('msg_file'):
            context['system_messages'] = get_messages(self.request.session['msg_file'], clear=True)
            del self.request.session['msg_file']
        return context

    def make_folder(self, title):
        """
        Make folder structure like
        <program>
            <videos>
            <pictures>
            <documents>
            <others>
        """
        try:
            folder_name = Transliterator.cleancyrillic(text=title)
            program_path = os.path.join(settings.MEDIA_ROOT, folder_name)
            os.makedirs(program_path, 0775)

            for folder in ['picture', 'video', 'document', 'other']:
                os.makedirs(os.path.join(program_path, folder), 0775)
            return True
        except IOError:
            return False

class ProgramList(ListView):
    model = Program
    template_name = 'programs/manage/program_list.html'
    context_object_name = 'programs'
    queryset = Program.objects.all().order_by('-title')
    paginate_by = settings.PAGINATE_BY

    def get_context_data(self, **kwargs):
        context = super(ProgramList, self).get_context_data(**kwargs)
        context['program_form'] = ProgramForm()
        context['annotate_by'] = settings.ANNOTATE_BY

        if self.request.session.has_key('msg_file'):
            context['system_messages'] = get_messages(self.request.session['msg_file'], clear=True)
            del self.request.session['msg_file']

        return context

class ProgramUpdate(UpdateView):
    form_class = ProgramForm
    model = Program
    success_url = '/manage/programs'
    template_name = 'programs/manage/program_update.html'
    context_object_name = 'program'

    def form_valid(self, form):
        object = form.save(commit=False)
        object.save()
        msg_filename = get_msgfile(self.request)
        messages = [{'type': 'success', 'message': _('Program successfully updated'), }]

        if set_messages(filename=msg_filename, messages=messages):
            self.request.session['msg_file'] = msg_filename

        return HttpResponseRedirect(self.get_success_url())

    def form_invalid(self, form):
        msg_filename = get_msgfile(self.request)
        messages = [{'type': 'errormsg', 'message': _('Please fill in the forms correctly'), }]

        if set_messages(filename=msg_filename, messages=messages):
            self.request.session['msg_file'] = msg_filename

        return super(ProgramUpdate, self).form_invalid(form)

    def get_object(self, queryset):
        return get_object_or_404(self.model, pk=self.kwargs.get('pk', None))

    def get_context_data(self, **kwargs):
        pk = self.kwargs.get('pk', None)
        context = super(ProgramUpdate, self).get_context_data(**kwargs)
        context['object_id'] = pk

        if self.request.session.has_key('msg_file'):
            context['system_messages'] = get_messages(self.request.session['msg_file'], clear=True)
            del self.request.session['msg_file']

        return context

class ProgramDelete(DeleteView):
    template_name = 'common/common_delete_template.html'
    success_url = '/manage/programs'
    context_object_name = 'item'

    def delete(self, request, *args, **kwargs):
        if 'delete' in self.request.POST['action'].lower():
            self.object = self.get_object()
            self.object.delete()

            msg_filename = get_msgfile(self.request)
            messages = [{
                'type': 'success',
                'message': _('Program successfully deleted'),
            }]

            if set_messages(filename=msg_filename, messages=messages):
                self.request.session['msg_file'] = msg_filename

        return HttpResponseRedirect(self.get_success_url())

    def get_context_data(self, **kwargs):
        context = super(ProgramDelete, self).get_context_data(**kwargs)
        context['form_action'] = self.request.META['PATH_INFO']

        return context

    def get_object(self, queryset=None):
        return get_object_or_404(Program, pk=self.kwargs.get('pk'))
